import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:intl/intl.dart';
import '../models/expense.dart';
import '../services/database_service.dart';
import '../utils/constants.dart';

class MonthDetailScreen extends StatefulWidget {
  final DateTime month;

  const MonthDetailScreen({
    Key? key,
    required this.month,
  }) : super(key: key);

  @override
  _MonthDetailScreenState createState() => _MonthDetailScreenState();
}

class _MonthDetailScreenState extends State<MonthDetailScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<Expense> _expenses = [];
  Map<String, double> _categoryTotals = {};

  @override
  void initState() {
    super.initState();
    _loadExpenses();
  }

  Future<void> _loadExpenses() async {
    final expenses = await _databaseService.getExpensesByMonth(widget.month);
    final categoryTotals = <String, double>{};

    for (var expense in expenses) {
      categoryTotals[expense.category] =
          (categoryTotals[expense.category] ?? 0) + expense.amount;
    }

    setState(() {
      _expenses = expenses;
      _categoryTotals = categoryTotals;
    });
  }

  List<PieChartSectionData> _getPieChartSections() {
    return _categoryTotals.entries.map((entry) {
      final color = Color(Constants.categoryColors[entry.key]!);
      return PieChartSectionData(
        value: entry.value,
        title: '${entry.key}\n¥${entry.value.toStringAsFixed(0)}',
        color: color,
        radius: 100,
        titleStyle: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(DateFormat('yyyy年MM月').format(widget.month)),
        centerTitle: true,
      ),
      body: _expenses.isEmpty
          ? const Center(
              child: Text(
                '本月暂无记账记录',
                style: TextStyle(fontSize: 16),
              ),
            )
          : SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    height: 300,
                    padding: const EdgeInsets.all(16),
                    child: PieChart(
                      PieChartData(
                        sections: _getPieChartSections(),
                        sectionsSpace: 2,
                        centerSpaceRadius: 40,
                      ),
                    ),
                  ),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: _expenses.length,
                    itemBuilder: (context, index) {
                      final expense = _expenses[index];
                      return Card(
                        margin: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 8),
                        child: ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Color(
                                Constants.categoryColors[expense.category]!),
                            child: Text(
                              expense.category[0],
                              style: const TextStyle(color: Colors.white),
                            ),
                          ),
                          title: Text(expense.description),
                          subtitle: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(expense.category),
                              Text(
                                DateFormat('yyyy-MM-dd HH:mm')
                                    .format(expense.date),
                                style: const TextStyle(
                                    fontSize: 12, color: Colors.grey),
                              ),
                            ],
                          ),
                          trailing: Text(
                            '¥${expense.amount.toStringAsFixed(2)}',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
    );
  }
}
